﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace CommunityToolkitMvvmDemo.Behaviors
{
    public class WaterMarkBehavior : Behavior<TextBox>
    {
        public string WaterMarkText { get; set; } = "";  // 水印文本
        public string IsNotNullForeground { get; set; } // 不为空的文本颜色
        private Brush waterMarkForeground;               // 水印颜色

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.LostFocus += AssociatedObject_LostFocus;
            AssociatedObject.GotFocus += AssociatedObject_GotFocus;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            AssociatedObject.LostFocus -= AssociatedObject_LostFocus;
            AssociatedObject.GotFocus -= AssociatedObject_GotFocus;
        }

        private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox != null && textBox.Text == WaterMarkText)
            {
                textBox.Text = "";
                waterMarkForeground = textBox.Foreground;
                textBox.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(IsNotNullForeground));
            }
        }

        private void AssociatedObject_LostFocus(object sender, RoutedEventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox != null && textBox.Text == "")
            {
                textBox.Text = WaterMarkText;
                textBox.Foreground = waterMarkForeground;
            }
        }

    }
}
